import { h } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import type { MenuOption } from 'naive-ui'
import { randomColorList } from '@/utils/index'
import ColorFont from '@/components/ColorFont.vue'

export type menuItem = MenuOption & {
  label: Function
  key: string
  path: string
  children?: Array<menuItem>
}

export function formatMenuData(
  routes: Array<RouteRecordRaw>,
  parent?: menuItem | undefined
): Array<menuItem> {
  const list: Array<menuItem> = []
  routes.forEach((item) => {
    let path = '/' + item.path
    if (parent) {
      path = parent.path + path
    }

    const menuItem: menuItem = {
      path: path,
      // 自定义渲染label
      label: () =>
        h(ColorFont, {
          title: (item?.meta?.title || item.name) as string,
          color: randomColorList(),
          trans: !!item?.meta?.title
        }),
      // label: () => item.name,
      key: path
    }
    if (item.children) {
      menuItem.children = formatMenuData(item.children, menuItem)
    }
    list.push(menuItem)
  })
  return list
}
